package com.buss.message.controller;
import com.buss.message.entity.BnsMessageEntity;
import com.buss.message.service.BnsMessageServiceI;
import com.buss.user.entity.BnsUsersInfoEntity;

import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.context.annotation.Scope;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;

import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.Map;

import org.jeecgframework.core.util.ExceptionUtil;



/**   
 * @Title: Controller
 * @Description: 消息表
 * @author onlineGenerator
 * @date 2016-08-25 15:34:18
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/bnsMessageController")
public class BnsMessageController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BnsMessageController.class);

	@Autowired
	private BnsMessageServiceI bnsMessageService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 消息表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/buss/message/bnsMessageList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(BnsMessageEntity bnsMessage,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BnsMessageEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsMessage, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.bnsMessageService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	
	/**
	 * 选择会员跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "chooseMb")
	public ModelAndView chooseMb(HttpServletRequest request) {
		//--author：zhoujf-----start----date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
		ModelAndView mv = new ModelAndView("com/buss/articlegroup/chooseMb"); 
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		mv.addObject("ids", ids);
		return mv;
		//--author：zhoujf-----end------date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
	}
	
	/**
	 * 会员显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridChooseMb")
	public void datagridChooseMb(BnsUsersInfoEntity bnsUsersEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BnsUsersInfoEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsUsersEntity);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	

	/**
	 * 删除消息表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(BnsMessageEntity bnsMessage, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		bnsMessage = systemService.getEntity(BnsMessageEntity.class, bnsMessage.getId());
		message = "消息表删除成功";
		try{
			bnsMessageService.delete(bnsMessage);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "消息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除消息表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "消息表删除成功";
		try{
			for(String id:ids.split(",")){
				BnsMessageEntity bnsMessage = systemService.getEntity(BnsMessageEntity.class, 
				id
				);
				bnsMessageService.delete(bnsMessage);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "消息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加消息表
	 * 
	 * @param ids
	 * XXX 后台添加消息的时候 默认接收人的 id会get不到  也没报错 直接 提示保存成功 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(BnsMessageEntity bnsMessage, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "消息表添加成功";
		try{
			//从前台获取用户id和用户名
			/**
			 * XXX 用户表 bns_users_info 主键直接改为 user_id 这样后台添加的消息 就直接 用user_id 而不是 主键Id
			 * 这边接受的还是 主键Id
			 */
			String userIds = request.getParameter("userId");	
			String[] myIds = userIds.split(",");
			String userNames = request.getParameter("userName");
			String[] myNames = userNames.split(",");
			//从前台获取其他字段
			String myTitle = request.getParameter("title");
			String myContent = request.getParameter("content");
			String myMsgTypes = request.getParameter("messageTypes");
			String myStates = request.getParameter("states");
			//循环保存实体
			for(int i=0;i<myIds.length;i++){
				if(myIds[i]!=""){
					//新建一个消息实体
					BnsMessageEntity myMsg = new BnsMessageEntity();
					
					//保存用户id和用户名到消息实体中
					myMsg.setReceiveId(myIds[i]);
					myMsg.setReceiveName(myNames[i]);
					//将其他字段添加进去
					myMsg.setTitle(myTitle);
					myMsg.setContent(myContent);
					myMsg.setMessageTypes(Integer.valueOf(myMsgTypes));
					myMsg.setStates(myStates);
					myMsg.setIsRead("N");	// Y已读，N未读
					//保存实体
					bnsMessageService.save(myMsg);
					
				}
			}
			
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "消息表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新消息表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(BnsMessageEntity bnsMessage, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "消息表更新成功";
		BnsMessageEntity t = bnsMessageService.get(BnsMessageEntity.class, bnsMessage.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(bnsMessage, t);
			
			//获取前台更改的用户id和用户名
			String userIds = request.getParameter("userId");
			String userNames = request.getParameter("userName");
			//保存前台传来的用户id和用户名
			t.setReceiveId(userIds);
			t.setReceiveName(userNames);
			
			bnsMessageService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "消息表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
 	/**
	 * 自定义按钮-sql增强-发送
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doSend")
	@ResponseBody
	public AjaxJson doSend(HttpServletRequest request,String ids) {
		AjaxJson j = new AjaxJson();
		message = "发送成功";
		try{
			for(String id:ids.split(",")){
				BnsMessageEntity t = systemService.getEntity(BnsMessageEntity.class,id);
				bnsMessageService.doSendSql(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "发送失败";
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 消息表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(BnsMessageEntity bnsMessage, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(bnsMessage.getId())) {
			bnsMessage = bnsMessageService.getEntity(BnsMessageEntity.class, bnsMessage.getId());
//			req.setAttribute("bnsMessagePage", bnsMessage);
			idandname(req, bnsMessage);
		}
		bnsMessage.setStates("1");
		req.setAttribute("bnsMessagePage", bnsMessage);
		return new ModelAndView("com/buss/message/bnsMessage-add");
	}
	/**
	 * 消息表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(BnsMessageEntity bnsMessage, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(bnsMessage.getId())) {
			bnsMessage = bnsMessageService.getEntity(BnsMessageEntity.class, bnsMessage.getId());
			req.setAttribute("bnsMessagePage", bnsMessage);
			idandname(req, bnsMessage);
		}
		return new ModelAndView("com/buss/message/bnsMessage-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","bnsMessageController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(BnsMessageEntity bnsMessage,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(BnsMessageEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsMessage, request.getParameterMap());
		List<BnsMessageEntity> bnsMessages = this.bnsMessageService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"消息表");
		modelMap.put(NormalExcelConstants.CLASS,BnsMessageEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("消息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,bnsMessages);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(BnsMessageEntity bnsMessage,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"消息表");
    	modelMap.put(NormalExcelConstants.CLASS,BnsMessageEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("消息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST) 
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<BnsMessageEntity> listBnsMessageEntitys = ExcelImportUtil.importExcel(file.getInputStream(),BnsMessageEntity.class,params);
				for (BnsMessageEntity bnsMessage : listBnsMessageEntitys) {
					bnsMessageService.save(bnsMessage);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	public void idandname(HttpServletRequest req, BnsMessageEntity bnsMessageEntity) {

//		req.setAttribute("userId", articleGroupInfoEntity.getAreaId());
		req.setAttribute("userName", bnsMessageEntity.getReceiveName()); //用于初始显示，可以达到勾选用户点击”确定“后，文本框里面显示用户名

	}
}
